package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WorkspaceService workspaceService;
    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //组装x轴数据集合
        ArrayList<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);

        //将每一天加入到集合中
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        ArrayList<Double> turnoverlist = new ArrayList<>();
        // 接下来根据日期数据，获得对应的y轴数据
        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.getTurnover(map);
            // 如果查询的数据是null，则设置0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverlist.add(turnover);

        }


//        将x、y轴数据按照接口文档格式要求，封装成一个VO对象返回
        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(datelist, ","))
                .turnoverList(StringUtils.join(turnoverlist, ","))
                .build();

        return reportVO;
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //组装x轴数据集合
        ArrayList<LocalDate> datelist = new ArrayList<>();
        datelist.add(begin);

        //将每一天加入到集合中
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        ArrayList<Integer> newUserlist = new ArrayList<>();//新增用户
        ArrayList<Integer> totalUserlist = new ArrayList<>();//总用户数

        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end", endTime);
            //总共的用户数
            Integer totalUser = userMapper.getUserCount(map);
            map.put("begin", beginTime);
            //新增的用户数
            Integer newUser = userMapper.getUserCount(map);

            newUserlist.add(newUser);
            totalUserlist.add(totalUser);

        }
        UserReportVO reportVO = UserReportVO.builder()
                .dateList(StringUtils.join(datelist, ","))
                .newUserList(StringUtils.join(newUserlist, ","))
                .totalUserList(StringUtils.join(totalUserlist, ","))
                .build();
        return reportVO;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> datelist = new ArrayList<>();


        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        List<Integer> ordersList = new ArrayList<>();
        List<Integer> validOrdersList = new ArrayList<>();
        for (LocalDate date : datelist) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);


            //查询每天的订单总数
            Integer ordersCount = getOrdersCount(beginTime, endTime, null);
            //查询每天的有效订单
            Integer validOrdersCount = getOrdersCount(beginTime, endTime, Orders.COMPLETED);

            ordersList.add(ordersCount);
            validOrdersList.add(validOrdersCount);

        }
        //获取订单总数
        Integer totalOrderCount = ordersList.stream().reduce(Integer::sum).get();
        //获取有效订单数
        Integer validOrderCount = validOrdersList.stream().reduce(Integer::sum).get();

        //获取订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount!=0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;

        }
        OrderReportVO reportVO = OrderReportVO
                .builder()
                .dateList(StringUtils.join(datelist, ","))
                .orderCountList(StringUtils.join(ordersList, ","))
                .validOrderCountList(StringUtils.join(validOrdersList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return reportVO;
    }

    private Integer getOrdersCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("begin", beginTime);
        map.put("end", endTime);
        map.put("status", status);

        return orderMapper.ordersCount(map);
    }


    /**
     * 销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> getTop10List=orderMapper.top10(beginTime,endTime);
        String namelist = StringUtils.join(getTop10List.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberlist = StringUtils.join(getTop10List.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");


        SalesTop10ReportVO top10ReportVO = SalesTop10ReportVO
                .builder()
                .nameList(namelist)
                .numberList(numberlist)
                .build();
        return top10ReportVO;
    }

    /**
     * 导出前30天数据
     * @param response
     */
    @Override
    public void exportExcel(HttpServletResponse response) throws IOException {
        //查询近30天的营业数据
        LocalDate beginDay = LocalDate.now().minusDays(30);
        LocalDate endDay = LocalDate.now().minusDays(1);

        LocalDateTime beginTime = LocalDateTime.of(beginDay, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(endDay, LocalTime.MAX);

        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime,endTime);

        //通过POI将数据写入到Excel文件中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        //基于模板文件创建一个新的Excel文件
        XSSFWorkbook excel = new XSSFWorkbook(is);

        //根据excel文件获取当前页
        XSSFSheet sheet1 = excel.getSheet("Sheet1");

        sheet1.getRow(1).getCell(1).setCellValue("时间:"+beginDay+"----"+endDay);

        //填入概要数据
        sheet1.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
        sheet1.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
        sheet1.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
        sheet1.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
        sheet1.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

        //填入明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = beginDay.plusDays(i);
            //查询某一天的营业数据
            BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            XSSFRow rown = sheet1.getRow(7 + i);
            rown.getCell(1).setCellValue(date.toString());
            rown.getCell(2).setCellValue(businessData1.getTurnover());
            rown.getCell(3).setCellValue(businessData1.getValidOrderCount());
            rown.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
            rown.getCell(5).setCellValue(businessData1.getUnitPrice());
            rown.getCell(6).setCellValue(businessData1.getNewUsers());

        }

        ServletOutputStream outputStream = response.getOutputStream();

        excel.write(outputStream);

        //关流
        excel.close();
        outputStream.close();
    }


}
